package com.bizmda.bizsip.sink.connector;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import com.bizmda.bizsip.common.BizException;
import com.bizmda.bizsip.config.AbstractSinkConfig;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class HttpSinkConnector extends AbstractSinkConnector implements ByteProcessInterface {
    private String url;
    private String contentType;
    private String charset;

    @Override
    public void init(AbstractSinkConfig sinkConfig) throws BizException {
        super.init(sinkConfig);
        this.url = (String) sinkConfig.getConnectorMap().get("url");
        this.contentType = StrUtil.blankToDefault((String) sinkConfig.getConnectorMap().get("content-type"), "application/octet-stream");
        this.charset = StrUtil.blankToDefault((String) sinkConfig.getConnectorMap().get("charset"), "utf-8");
        log.info("初始化HttpSinkConnector:url[{}],content-type[{}],charset[{}]", this.url, this.contentType, this.charset);
    }

    @Override
    public byte[] process(byte[] inMessage) throws BizException {
        HttpResponse httpResponse;
        String urlString;
        httpResponse = HttpUtil.createPost(this.url)
                .header("Content-Type",this.contentType)
                .body(inMessage).charset(this.charset)
                .execute().charset(this.charset);
        return httpResponse.bodyBytes();
    }
}
